var async = require('async'),
    needle = require('needle'),
    querystring = require('querystring'),
    crypto = require('crypto');
var fs = require('fs');

// 导出属性 
var common = {
    readdir:function (root, callback) {
        //遍历读取文件
        function readFile(path, filesList, targetObj) {
            // console.log(path);
            var files = fs.readdirSync(path); //需要用到同步读取
            files.forEach(walk);
            function walk(file) {
                path=path.replace(/\\/g,'/');
                states = fs.statSync(path + '/' + file);
                if (states.isDirectory()) {
                    var item;
                    if (targetObj["folder"]) {
                        item = {name: file, folder: []};
                        targetObj["folder"].push(item);
                    }
                    else {
                        item = {name: file, folder: []};
                        filesList.push(item);
                    }
                    readFile(path + '/' + file, filesList, item);
                } else {
                    //创建一个对象保存信息
                    var obj = {};
                    obj.size = states.size;//文件大小，以字节为单位
                    obj.name = file;//文件名
                    obj.path = path + '/' + file; //文件绝对路径

                    if (targetObj["folder"]) {
                        targetObj["folder"].push({name: file, url: obj.path});
                    }
                    else {
                        filesList.push({name: file, url: obj.path});
                    }
                }
            }
        }
        function geFileList(path) {
            var filesList = [];
            var targetObj = {};
            readFile(path, filesList, targetObj);
            return filesList;
        }
        callback(geFileList(root));
    },
    readFile:function (path, callback) {
        fs.readFile(path, function (err, data) {
            callback(err, data.toString() );
        });
    }
};



exports.common = common;
